package woa.queue;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

/**
 * 01 矩阵
 * 给定一个由 0 和 1 组成的矩阵 mat ，请输出一个大小相同的矩阵，其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。
 * 两个相邻元素间的距离为 1 。
 *
 * 输入：mat = [[0,0,0],[0,1,0],[1,1,1]]
 * 输出：[[0,0,0],[0,1,0],[1,2,1]]
 *
 * @author wangpeng
 * @date 2021/12/2
 */
public class UpdateMatrixProblem {

    public static int[][] updateMatrix(int[][] mat) {
        int rLen = mat.length;
        int cLen = mat[0].length;
        boolean[][] visited = new boolean[rLen][cLen];
        Queue<int[]> queue = new ArrayDeque<>();

        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                if (mat[i][j] == 0) {
                    queue.offer(new int[]{i, j});
                    visited[i][j] = true;
                }
            }
        }

        int count = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] cell = queue.poll();
                int m = cell[0];
                int n = cell[1];
                //up
                if (m - 1 >= 0 && !visited[m - 1][n]) {
                    mat[m - 1][n] = count;
                    queue.offer(new int[]{m - 1, n});
                    visited[m - 1][n] = true;
                }
                //down
                if (m + 1 < rLen && !visited[m + 1][n]) {
                    mat[m + 1][n] = count;
                    queue.offer(new int[]{m + 1, n});
                    visited[m + 1][n] = true;
                }
                //lfet
                if (n - 1 >= 0 && !visited[m][n - 1]) {
                    mat[m][n - 1] = count;
                    queue.offer(new int[]{m, n - 1});
                    visited[m][n - 1] = true;
                }
                //right
                if (n + 1 < cLen && !visited[m][n + 1]) {
                    mat[m][n + 1] = count;
                    queue.offer(new int[]{m, n + 1});
                    visited[m][n + 1] = true;
                }
            }
            count++;
        }

        return mat;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.deepToString(updateMatrix(new int[][]{{0, 0, 0}, {0, 1, 0}, {1, 1, 1}})));
    }
}
